package cn.ihna.demo.server.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

/**
 * @author xianyingda@gmail.com
 * @serial
 * @since 2020-08-15 01:18
 */
public class NettyServer {
    private int port;


    public NettyServer(int port) {
        this.port = port;
    }

    public void start() throws Exception {
        // 线程组
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            // 客户端启动必备
            ServerBootstrap b = new ServerBootstrap();
            final EchoServerHandler handler = new EchoServerHandler();
            b.group(group) // 传入线程组
                    .channel(NioServerSocketChannel.class) // 指定使用nio进行网络通信
                    .localAddress(new InetSocketAddress(port))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(handler);
                        }
                    })
            ;
            // 监听端口
            ChannelFuture f = b.bind().sync();

            // 阻塞close事件 防止程序退出
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws Exception {
        NettyServer nettyServer = new NettyServer(10010);
        System.out.println("server ready");
        nettyServer.start();
        System.out.println("server close");
    }
}
